<template>
  <div class="upload_table">
    <el-upload
      v-model:file-list="fileList"
      class="upload-demo"
      action="#"
      :on-change="handleChange"
      :http-request="handleRequestInfo"
      drag
      list-type="text"
      :on-success="successfun"
      :name="props?.postImage"
      multiple
      :before-upload="beforeAvatarUpload"
    >
      <!-- //文件列表类型，text/picture/picture-card -->
      <!-- accept="image/jpg, image/jpeg, image/png" -->

      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
      <div></div>

      <template #tip>
        <div class="el-upload__tip">
          {{ tipMsg }}
        </div>
      </template>
    </el-upload>

    <div v-if="fileListShow">
      <div class="th_tr">
        <div style="width: 50%" class="upload_th">文件名称</div>
        <div style="width: 30%" class="upload_th">文件类型</div>
        <div class="upload_th">操作</div>
      </div>


      <div v-if="fileList.length<1"  style="padding: 100px 40px 100px;display: flex;justify-content: center;">
            <img :src="EmptyPng" style="object-fit: cover; height: 130px" />
      </div>

      <div v-else class="file_ever" v-for="(item, index) in fileList">
        <div class="td" style="width: 50%">{{ item.name }}</div>
        <div class="td" style="width: 30%">{{ item.type }}</div>
        <div class="td">
          <el-button type="danger" link @click="delfile(fileList, index)"> 删除 </el-button>
        </div>

        <div v-if="item.percentage" class="progress_div">
          <el-progress v-if="item.percentage < 100" :percentage="item.percentage" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { uploadFiles } from "@/api/modules/upload";
import EmptyPng from "@/assets/images/empty.png";
import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";

import type { UploadProps } from "element-plus";

const props = withDefaults(
  defineProps<{
    path: string;
    params?: Record<string, any>;
    postImage?: string; //  提交的数据名称 ==> 非必传
    fileListShow?: boolean;
    tipMsg?: string;
  }>(),
  {
    params: () => ({}),
    fileListShow: true, // 设置默认值
    tipMsg: "传入文件小于20M"
  }
);

const fileList = defineModel<Array<Record<string, any>>>({ default: [] });

const beforeAvatarUpload: UploadProps["beforeUpload"] = async rawFile => {
  let result = false;

  await new Promise((resolve, reject) => {
    var reader = new FileReader();
    reader.onload = function (event) {
      // if (rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/jpeg') {
      //     ElMessage.error('图片仅支持jpg、jpeg、png格式!')
      //     return reject(false);
      //   }

      if (rawFile.size / 1024 / 1024 > 20) {
        ElMessage.error("图片大小不能超过20M!");
        return reject(false);
      }

      var txt = event.target.result;
      var img = document.createElement("img");
      img.src = txt;
      //  img.onload = function () {
      //     if (img.width > 100 || img.height > 100) {
      //       ElMessage.error('图片尺寸最大为100*100')
      //       return reject(false);
      //     }
      //     resolve(true)
      //   }
      resolve(true);
    };
    reader.readAsDataURL(rawFile);
  })
    .then(res => {
      result = true;
    })
    .catch(er => {
      result = false;
    });
  return result;
};

const delfile = (uploadFiles, index) => {
  uploadFiles.splice(index, 1);
};

const getFileData = () => {
  var fileData = [];

  var uploadFiles = JSON.parse(JSON.stringify(fileList.value));
  console.log("----------------------");
  console.log(uploadFiles);

  for (let index = 0; index < uploadFiles.length; index++) {
    const element = uploadFiles[index];
    var _obj = {};
    _obj["name"] = element.name;
    _obj["size"] = element.size;
    _obj["type"] = element.type;
    _obj["url"] = element.url;
    fileData.push(_obj);
  }

  return fileData;
};

defineExpose({
  getFileData
});

//  const successfun = async (aa, bb) => {
//   console.log(aa,bb)

//   console.log('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')

//  }
const handleRequestInfo = async (options, type) => {
  console.log(options);

  const formData = new FormData();
  console.log(formData);
  formData.append(options.filename, options.file);
  uploadFiles(props.path, props.params, formData, evt => {
    console.log(evt);
    options.onProgress(evt);
  })
    .then(({ code, data, message }) => {
      if (code == ResultEnum.SUCCESS) {
        console.log(data);
        options.onSuccess(data);
      } else {
        console.log(code, data, message);
        failMsg(message);
        clear_fail_file();
      }
    })
    .catch(err => {
      failMsg("上传失败");
      clear_fail_file();
    });
};

const clear_fail_file = () => {
  var uploadFiles = JSON.parse(JSON.stringify(fileList.value));
  console.log("----------------------");
  console.log(uploadFiles);

  for (let index = 0; index < uploadFiles.length; index++) {
    const element = uploadFiles[index];
    console.log(element.status);
    if (element.status == "success" || element.status == "ready") {
    } else {
      uploadFiles.splice(index, 1);
    }
  }
  console.log(uploadFiles);
  fileList.value = uploadFiles;
};

const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  // fileList.value = fileList.value.slice(-3)
  console.log(uploadFile);
  console.log(uploadFile.response);

  var go_check = 0;
  console.log(uploadFiles.length);
  for (let index = 0; index < uploadFiles.length; index++) {
    const element = uploadFiles[index];
    if (element.response) {
      element["type"] = element.response.type;
      element["url"] = element.response.url;
    }
  }
};
</script>

<style scoped>
:deep(.el-upload-list) {
  display: none;
}

:deep(.el-button--danger.is-link, .el-button--danger.is-plain, .el-button--danger.is-text) {
  text-align: left;
  align-items: start;
  justify-content: left;
}

.file_ever {
  position: relative;
}

.progress_div {
  position: absolute;
  bottom: 27px;
  left: 0;
  width: 100%;
}

.upload_table {
  position: relative;

  .th_tr {
    margin-top: 20px;

    display: flex;
    background-color: #f5f8fa;
    width: 100%;

    .upload_th {
      height: 40px;
      padding: 0 16px;
      line-height: 40px;
      color: #646567;
      font-size: 12px;
    }
  }

  :deep(.el-upload-list) {
    padding-top: 50px;
  }
}

.avatar-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
}

.file_ever {
  display: flex;

  .td {
    height: 40px;
    padding: 0 16px;
    line-height: 40px;
    color: #646567;
    font-size: 12px;
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
}
</style>
